<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统功能全面测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            background-color: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .test-section {
            margin-bottom: 20px;
            padding: 15px;
            background-color: white;
            border-radius: 4px;
        }
        h2 {
            color: #444;
            margin-top: 0;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .result {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            white-space: pre-wrap;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .step {
            margin-bottom: 10px;
        }
        input[type="text"], input[type="password"] {
            padding: 8px;
            width: 100%;
            box-sizing: border-box;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>系统功能全面测试</h1>
        
        <div class="test-section">
            <h2>1. 环境信息</h2>
            <button id="checkEnvBtn">检查环境</button>
            <div id="envResult" class="result"></div>
        </div>
        
        <div class="test-section">
            <h2>2. 用户登录</h2>
            <input type="text" id="username" placeholder="用户名 (默认: admin)" value="admin">
            <input type="password" id="password" placeholder="密码 (默认: admin123)" value="admin123">
            <button id="loginBtn">登录</button>
            <div id="loginResult" class="result"></div>
        </div>
        
        <div class="test-section">
            <h2>3. 获取用户列表</h2>
            <button id="getUsersBtn">获取用户列表</button>
            <div id="usersResult" class="result"></div>
        </div>
        
        <div class="test-section">
            <h2>4. 系统状态检查</h2>
            <button id="checkStatusBtn">检查系统状态</button>
            <div id="statusResult" class="result"></div>
        </div>
        
        <div class="test-section">
            <h2>5. 一键完整测试</h2>
            <button id="fullTestBtn" style="background-color: #2196F3;">运行完整测试</button>
            <div id="fullTestResult" class="result"></div>
        </div>
    </div>

    <script>
        // 全局变量存储token
        let token = null;
        
        // API基础URL
        const API_BASE_URL = 'http://localhost:8080';
        
        // 工具函数：显示结果
        function showResult(elementId, content, type = 'info') {
            const element = document.getElementById(elementId);
            element.textContent = content;
            element.className = 'result ' + type;
        }
        
        // 工具函数：发送API请求
        async function sendRequest(url, method = 'GET', data = null, useToken = false) {
            const options = {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                }
            };
            
            if (useToken && token) {
                options.headers['Authorization'] = `Bearer ${token}`;
            }
            
            if (data) {
                options.body = JSON.stringify(data);
            }
            
            try {
                const response = await fetch(url, options);
                const result = await response.json();
                return { success: response.ok, data: result, status: response.status };
            } catch (error) {
                return { success: false, error: error.message };
            }
        }
        
        // 1. 检查环境
        document.getElementById('checkEnvBtn').addEventListener('click', async function() {
            showResult('envResult', '正在检查环境...');
            
            try {
                // 检查后端API连接
                const backendResult = await fetch(API_BASE_URL + '/api/system/health', {
                    method: 'GET',
                    timeout: 5000
                }).then(res => res.ok ? '连接成功' : '连接失败');
                
                // 检查前端服务
                const frontendResult = '运行中';
                
                // 检查浏览器兼容性
                const browserResult = '支持';
                
                const result = `前端服务: ${frontendResult}\n后端API: ${backendResult}\n浏览器兼容性: ${browserResult}\n当前时间: ${new Date().toLocaleString()}`;
                showResult('envResult', result, 'success');
            } catch (error) {
                showResult('envResult', `环境检查失败: ${error.message}`, 'error');
            }
        });
        
        // 2. 用户登录
        document.getElementById('loginBtn').addEventListener('click', async function() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            showResult('loginResult', '正在登录...');
            
            try {
                const result = await sendRequest(
                    API_BASE_URL + '/api/login',
                    'POST',
                    { username, password }
                );
                
                if (result.success && result.data.code === 200 && result.data.data) {
                    token = result.data.data;
                    showResult('loginResult', `登录成功！\nToken: ${token.substring(0, 20)}...`, 'success');
                } else {
                    showResult('loginResult', `登录失败: ${result.data?.msg || '未知错误'}`, 'error');
                }
            } catch (error) {
                showResult('loginResult', `登录请求失败: ${error.message}`, 'error');
            }
        });
        
        // 3. 获取用户列表
        document.getElementById('getUsersBtn').addEventListener('click', async function() {
            if (!token) {
                showResult('usersResult', '请先登录获取Token', 'error');
                return;
            }
            
            showResult('usersResult', '正在获取用户列表...');
            
            try {
                const result = await sendRequest(
                    API_BASE_URL + '/api/users/list',
                    'GET',
                    null,
                    true
                );
                
                if (result.success && result.data.code === 200) {
                    const users = result.data.data || [];
                    showResult('usersResult', `获取成功！共${users.length}个用户\n${JSON.stringify(users, null, 2)}`, 'success');
                } else {
                    showResult('usersResult', `获取失败: ${result.data?.msg || '未知错误'}`, 'error');
                }
            } catch (error) {
                showResult('usersResult', `请求失败: ${error.message}`, 'error');
            }
        });
        
        // 4. 检查系统状态
        document.getElementById('checkStatusBtn').addEventListener('click', async function() {
            showResult('statusResult', '正在检查系统状态...');
            
            try {
                // 检查各种系统组件
                const components = [
                    { name: '认证服务', url: '/api/auth/check' },
                    { name: '用户服务', url: '/api/users/count' },
                    { name: '菜单服务', url: '/api/menus' }
                ];
                
                const results = [];
                for (const component of components) {
                    try {
                        const result = await sendRequest(
                            API_BASE_URL + component.url,
                            'GET',
                            null,
                            true
                        );
                        results.push(`${component.name}: ${result.success ? '正常' : '异常'}`);
                    } catch (error) {
                        results.push(`${component.name}: 异常 (${error.message})`);
                    }
                }
                
                showResult('statusResult', results.join('\n'), 'info');
            } catch (error) {
                showResult('statusResult', `系统状态检查失败: ${error.message}`, 'error');
            }
        });
        
        // 5. 一键完整测试
        document.getElementById('fullTestBtn').addEventListener('click', async function() {
            showResult('fullTestResult', '开始完整测试...\n\n');
            
            const results = [];
            
            try {
                // 步骤1: 检查环境
                results.push('===== 步骤1: 检查环境 =====');
                showResult('fullTestResult', results.join('\n'));
                
                // 步骤2: 登录
                results.push('\n===== 步骤2: 用户登录 =====');
                showResult('fullTestResult', results.join('\n'));
                
                const username = document.getElementById('username').value;
                const password = document.getElementById('password').value;
                
                const loginResult = await sendRequest(
                    API_BASE_URL + '/api/login',
                    'POST',
                    { username, password }
                );
                
                if (loginResult.success && loginResult.data.code === 200 && loginResult.data.data) {
                    token = loginResult.data.data;
                    results.push('登录成功！');
                } else {
                    results.push(`登录失败: ${loginResult.data?.msg || '未知错误'}`);
                    showResult('fullTestResult', results.join('\n'), 'error');
                    return;
                }
                
                // 步骤3: 获取用户列表
                results.push('\n===== 步骤3: 获取用户列表 =====');
                showResult('fullTestResult', results.join('\n'));
                
                const usersResult = await sendRequest(
                    API_BASE_URL + '/api/users/list',
                    'GET',
                    null,
                    true
                );
                
                if (usersResult.success && usersResult.data.code === 200) {
                    const users = usersResult.data.data || [];
                    results.push(`获取成功！共${users.length}个用户`);
                } else {
                    results.push(`获取失败: ${usersResult.data?.msg || '未知错误'}`);
                }
                
                // 步骤4: 检查其他API
                results.push('\n===== 步骤4: 检查其他API =====');
                showResult('fullTestResult', results.join('\n'));
                
                // 完成测试
                results.push('\n===== 测试完成 =====');
                results.push('测试执行时间: ' + new Date().toLocaleString());
                
                showResult('fullTestResult', results.join('\n'), 'success');
            } catch (error) {
                results.push(`测试失败: ${error.message}`);
                showResult('fullTestResult', results.join('\n'), 'error');
            }
        });
        
        // 页面加载时自动检查环境
        window.onload = function() {
            document.getElementById('checkEnvBtn').click();
        };
    </script>
</body>
</html>